package com.example.studentmgt.service;

import com.alibaba.fastjson.JSONObject;
import com.example.studentmgt.client.Client;
import com.example.studentmgt.dao.StudentDao;
import com.example.studentmgt.model.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class StudentService {
    private final static Logger log = LoggerFactory.getLogger(StudentService.class);

    @Resource
    private StudentDao studentDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private Client client;

    public static String createRandomStr(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(52);
            stringBuffer.append(str.charAt(number));
        }
        return stringBuffer.toString();
    }

    //查所有用户
    public List<Student> queryAll() {
        return studentDao.queryAll();
    }

    /**
     * 获取用户策略:先从缓存中获取用户，没有则读mysql数据，再将数据写入缓存
     *
     * @param id
     */
    public Student findStudentById(Long id) {
        Student student = studentDao.findStudentById(id);
        log.info("fetch data from pg:" + student.getName());
        log.info(JSONObject.toJSONString(student));
        return student;
    }

    //删除用户策略:删除数据表中数据，然后删除缓存
    public int deleteStudentById(Long id) {
        int result = studentDao.deleteStudentById(id);
        String key = "student_" + id;
        if (result != 0) {
            boolean hasKey = redisTemplate.hasKey(key);
            if (hasKey) {
                redisTemplate.delete(key);
                log.info("delete redis key:" + key);
            }
        }
        return result;
    }

    /**
     * 更新用户策略：先更新数据表，成功之后，删除原来的缓存，再更新缓存
     */
    public int updateStudent(Student student) {
        ValueOperations<String, Student> operations = redisTemplate.opsForValue();
        int result = studentDao.updateStudent(student);
        if (result != 0) {
            String key = "student_" + student.getId();
            boolean haskey = redisTemplate.hasKey(key);
            if (haskey) {
                redisTemplate.delete(key);
                log.info("delete redis key:" + key);
            }
            // 再将更新后的数据加入缓存
            Student studentNew = studentDao.findStudentById(student.getId());
            if (studentNew != null) {
                operations.set(key, studentNew, 3, TimeUnit.MINUTES);
            }
        }
        return result;
    }

    public Student student() {
        Student student = new Student();
        student.setName(createRandomStr(8));
        student.setAge(new Random().nextInt(100));
        studentDao.saveStudent(student);
        return student;
    }

    public Student cachedStudentById(Long id) {
        String key = "student_" + id;
        ValueOperations<String, Student> operations = redisTemplate.opsForValue();
        //判断redis中是否有键为key的缓存
        boolean hasKey = redisTemplate.hasKey(key);
        Student student;
        if (hasKey) {
            student = operations.get(key);
            log.info("fetch data from redis:" + student.getName());
        } else {
            student = studentDao.findStudentById(id);
            log.info("fetch data from pg:" + student.getName());
            //写入缓存
            operations.set(key, student, 3, TimeUnit.MINUTES);
        }
        return student;
    }

    public List<Student> top() {
        return studentDao.top();
    }
}
